package com.easy.util;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;
import java.util.Random;

public class EmailUtil {
    public static final String FROM= "2870520736@qq.com";
    public static final String AUTH_CODE= "xyolrqhyzdxjdfgd";
    public static final String HOST= "smtp.qq.com";
    public static final String PORT= "465";
    private static final Session session;
    private static final int length= 5;
    static {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.ssl.enable", "true");

        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, AUTH_CODE);
            }
        });
       // session.setDebug(true);
    }
    public static String getCode(){
        String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder code=new StringBuilder();
        Random random=new Random();
        for(int i=0;i<length;i++){
            code.append(chars.charAt(random.nextInt(chars.length())));
        }
        return code.toString();
    }

    public static void sendEmail(String to, String text){
        Message message=new MimeMessage( session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("登录验证码");

            String content = "<div style='padding:30px; background:#000; text-align:center; font-family: Arial, sans-serif; border-radius: 10px; max-width: 500px; margin: 0 auto;'>" +
                    "<h2 style='color:#fff; margin-bottom: 20px; font-weight: normal;'>您的验证码是：</h2>" +
                    "<h1 style='color:#fff; font-size:42px; letter-spacing:8px; background: #333; padding: 20px; border-radius: 8px; display: inline-block;'>" + text + "</h1>" +
                    "<p style='color:#aaa; margin-top: 25px; font-size: 14px;'>验证码有效期为5分钟，请尽快使用。</p>" +
                    "<hr style='border: none; border-top: 1px solid #333; margin: 20px 0;'/>" +
                    "<p style='color:#666; font-size: 12px;'>此邮件由 easyTravel 系统自动发送，请勿回复。</p>" +
                    "</div>";
           // message.setText(text);
            message.setContent(content, "text/html;charset=UTF-8");
            Transport.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
//    public static String sendCode(String to){
//        String code=getCode();
//        sendEmail(to, code);
//        return code;
//    }
    public static void main(String[] args) {
//        sendEmail("2870520736@qq.com","登录验证码");
    }
}
